import 'package:awak/common/db/db_helper.dart';
import 'package:awak/common/models/topic.dart';

class TopicRepository {
  // 新增主题
  Future<int> addTopic(Topic topic) async {
    final db = await DBHelper.database;
    return await db.insert('topic', topic.toMap());
  }

  // 获取所有主题
  Future<List<Topic>> getAllTopics() async {
    final db = await DBHelper.database;
    final res = await db.query('topic');
    return res.map((e) => Topic.fromMap(e)).toList();
  }

  // 根据标签获取主题
  Future<Topic?> getTopicByLabel(String label) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'topic',
      where: 'label = ?',
      whereArgs: [label],
      limit: 1,
    );
    if (res.isNotEmpty) {
      return Topic.fromMap(res.first);
    }
    return null;
  }

  // 删除主题
  Future<int> deleteTopic(int id) async {
    final db = await DBHelper.database;
    return await db.delete('topic', where: 'id = ?', whereArgs: [id]);
  }

  // 更新主题
  Future<int> updateTopic(Topic topic) async {
    final db = await DBHelper.database;
    return await db.update('topic', topic.toMap(), where: 'id = ?', whereArgs: [topic.id]);
  }

  // 更新主题参与人数
  Future<int> updateTopicPeople(int id, int numberPeople) async {
    final db = await DBHelper.database;
    return await db.update(
      'topic',
      {'numberPeople': numberPeople},
      where: 'id = ?',
      whereArgs: [id],
    );
  }
}
